//
//  JCContactsViewController.swift
//  JChat
//
//  Created by JIGUANG on 2017/2/16.
//  Copyright © 2017年 HXHG. All rights reserved.
//

import UIKit
import YHPopupView
import RxSwift
import RxCocoa
import JXCategoryView
import JXPagingView
import MTCategory
import YPNavigationBarTransition
import JXSegmentedView


class JCContactsViewController: BaseViewController {
    
    public required override init() {
        super.init()
        //NotificationCenter.default.addObserver(self, selector: #selector(_updateBadge), name: NSNotification.Name(rawValue: kUpdateVerification), object: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    required public init(rounterParams params: Dictionary<String, Any>?) {
        fatalError("init(rounterParams:) has not been implemented")
    }
    
    private let userProvider: MTProvider<UserCenterApi> = MTProvider<UserCenterApi>()
    
    //MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.theme.background
        _init()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //_updateBadge()
    }

    deinit {
        //NotificationCenter.default.removeObserver(self)
    }
    
    
    fileprivate lazy var contacterView: UITableView = {
        var contacterView = UITableView(frame: .zero, style: .grouped)
        contacterView.delegate = self
        contacterView.dataSource = self
        contacterView.separatorStyle = .none
        contacterView.sectionIndexBackgroundColor = UIColor.clear
        contacterView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)
        return contacterView
    }()
    
    fileprivate var badgeCount = 0
    private var bag = DisposeBag()
    //fileprivate lazy var tagArray = ["验证消息", "俱乐部消息"]
    //fileprivate lazy var tagArray = ["验证消息"]
    fileprivate lazy var users: [JMSGUser] = []

    fileprivate lazy var keys: [String] = []
    fileprivate lazy var data: Dictionary<String, [JMSGUser]> = Dictionary()
    
    public var listViewDidScrollCallback: ((UIScrollView) -> ())?
    
    lazy var searchBarView: PagingViewTableHeaderView = {
        let v = PagingViewTableHeaderView()
        v.delegate = self
        v.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 56)
        return v
    }()
    
    //MARK: - private func
    private func _init() {
        self.title = "通讯录"
        
        if #available(iOS 10.0, *) {
            navigationVC?.tabBarItem.badgeColor = UIColor(hex: 0xEB424C)
        }
        
        contacterView.register(JCContacterCell.self, forCellReuseIdentifier: "JCContacterCell")
        contacterView.register(JCContacterFriendCell.self, forCellReuseIdentifier: JCContacterFriendCell.reuseIdentity())
        contacterView.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
        GroupTableSeparatorFix.removeFirstAndLastSeparatorLine()
        contacterView.backgroundColor = UIColor.theme.background
        contacterView.estimatedSectionHeaderHeight = 0
        contacterView.estimatedSectionFooterHeight = 0
        contacterView.separatorStyle = .none
        
        contacterView.tableHeaderView = searchBarView
        
        view.addSubview(contacterView)
        
        contacterView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        _getFriends()
        _updateBadge()
        
        NotificationCenter.default.addObserver(self, selector: #selector(_updateUserInfo), name: NSNotification.Name(rawValue: kUpdateFriendInfo), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(_getFriends), name: NSNotification.Name(rawValue: kUpdateFriendList), object: nil)
        
//        JMSGFriendManager.removeFriend(withUsername: "test1", appKey: JPushAppSecretKey) { (result, error) in
//
//        }
    }
    

    @objc func _updateUserInfo() {
        _classify(users)
        contacterView.reloadData()
    }
    
    func _classify(_ users: [JMSGUser]) {
        self.users = users
        keys.removeAll()
        data.removeAll()
        for item in users {
            var key = item.displayName().firstCharacter()
            if !key.isLetterOrNum() {
                key = "#"
            }
            var array = data[key]
            if array == nil {
                array = [item]
            } else {
                array?.append(item)
            }
            if !keys.contains(key) {
                keys.append(key)
            }
            data[key] = array
        }
        keys = keys.sortedKeys()
    }
    
    @objc func _getFriends() {
        JMSGFriendManager.getFriendList { (result, error) in
            if let users = result as? [JMSGUser] {
                self._classify(users)
                self.contacterView.reloadData()
            }
        }
    }
        
    //MARK: - click func
    @objc func _clickNavRightButton(_ sender: UIButton) {
        navigationVC?.pushViewController(JCSearchFriendViewController(), animated: true)
    }
    
    @objc func _updateBadge() {
        if UserDefaults.standard.object(forKey: kUnreadInvitationCount) != nil {
            badgeCount = UserDefaults.standard.object(forKey: kUnreadInvitationCount) as! Int
        } else {
            badgeCount = 0
        }
        if badgeCount > 99 {
            navigationVC?.tabBarItem.badgeValue = "99+"
        } else {
            navigationVC?.tabBarItem.badgeValue = badgeCount == 0 ? nil : "\(badgeCount)"
        }
        //contacterView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .none)
        contacterView.reloadData()
    }
    
}

extension JCContactsViewController: PagingViewTableHeaderViewDelegate {
    func textFieldShouldBeginEditing(_ textField: UITextField) {
        let searchVC: MTSearchAddFriendViewController = MTSearchAddFriendViewController()
        //navigationController?.pushViewController(MTSearchAddFriendViewController(), animated: true)
        let nav = BaseNavController(rootViewController: searchVC)
        nav.modalPresentationStyle = .fullScreen
        nav.modalTransitionStyle = .crossDissolve
        self.navigationVC?.present(nav, animated: true, completion: nil)
    }
}

//Mark: -
extension JCContactsViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if users.count > 0 {
            return keys.count
        }
        return 0
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        if section == 0 {
//            return tagArray.count
//        }
        return data[keys[section]]?.count ?? 0
    }
    
//    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
////        if section == 0 {
////            return ""
////        }
//        return keys[section]
//    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let l = MTContacterSectionHeaderView()
        l.setTitle(title: keys[section])
        return l
    }
    
    /// 快速索引
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return keys
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //
//        if indexPath.section == 0 {
//            return tableView.dequeueReusableCell(withIdentifier: "JCContacterCell", for: indexPath)
//        }
        let cell: JCContacterFriendCell = tableView.dequeueReusableCell(withIdentifier: JCContacterFriendCell.reuseIdentity(), for: indexPath) as! JCContacterFriendCell
        
        let userData: JMSGUser = data[keys[indexPath.section]]![indexPath.row]
        
        cell.bindDate(userData)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        guard let cell = cell as? JCContacterCell else {
            return
        }
//        if indexPath.section == 0 {
//            switch indexPath.row {
//            case 0:
//                cell.title = "验证消息"
//                cell.icon = UIImage.loadImage("com_icon_friend_tip")
//                cell.isShowBadge = badgeCount > 0 ? true : false
//            case 1:
//                cell.title = "我的俱乐部"
//                cell.icon = UIImage(named: "placeholder-square")
//                cell.isShowBadge = false
//            default:
//                break
//            }
//            return
//        }
        let user = data[keys[indexPath.section]]?[indexPath.row]
        cell.isShowBadge = false
        cell.bindDate(user!)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
//        if indexPath.section == 0 {
//            switch indexPath.row {
//            case 0:
//                navigationVC?.pushViewController(JCIdentityVerificationViewController(), animated: true)
//            case 1:
//                navigationVC?.pushViewController(JCGroupListViewController(), animated: true)
//            default:
//                break
//            }
//            return
//        }
//        let vc = JCUserInfoViewController()
        let user = data[keys[indexPath.section]]?[indexPath.row]
//        vc.user = user
//        navigationVC?.pushViewController(vc, animated: true)
//        let c = MineViewController(username: user?.username)
//        self.navigationVC?.pushViewController(c, animated: true)
        //UserDefaults.standard.set(0, forKey: kUnreadInvitationCount)
        JMSGConversation.createSingleConversation(withUsername: (user?.username)!) { (result, error) in
            if error == nil {
                let conv = result as! JMSGConversation
                let vc = JCChatViewController(conversation: conv)
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateConversation), object: nil, userInfo: nil)
                self.navigationVC?.pushViewController(vc, animated: true)
            }
        }
        
//        JMSGConversation.createSingleConversation(withUsername: (user?.username)!, appKey: (user?.appKey)!) { (result, error) in
//            if error == nil {
//                let conv = result as! JMSGConversation
//                let vc = JCChatViewController(conversation: conv)
//                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateConversation), object: nil, userInfo: nil)
//                self.navigationController?.pushViewController(vc, animated: true)
//            }
//        }
        

    }
}

extension JCContactsViewController {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.listViewDidScrollCallback?(scrollView)
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
        return false
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let deleteAction:UIContextualAction = UIContextualAction(style: .destructive, title: "") { (action, sourceView, completionHandler) in
            completionHandler(true)
            self.deleteFriend(indexPath)
        }
        deleteAction.image = UIImage(named: "icon_trash")
        deleteAction.backgroundColor = UIColor(hex: 0xFFC000)
        let actions:[UIContextualAction] = [deleteAction]
        let action:UISwipeActionsConfiguration = UISwipeActionsConfiguration(actions: actions)
        action.performsFirstActionWithFullSwipe = false
        return action
    }
    
    private func deleteFriend(_ indexPath: IndexPath) {
        UIAlertController.rx.show(in: self, title: nil, message: "确认要删除好友？", buttons: [.cancel("取消"), .default("确认")]).subscribe(onSuccess: { [weak self] index in
            guard let weakSelf = self else { return }
            if index == 1 {
                if let user = weakSelf.data[weakSelf.keys[indexPath.section]]?[indexPath.row] {
                    JMSGFriendManager.removeFriend(withUsername: user.username, appKey: user.appKey) { (result, error) in
                        if error == nil {
                            
                            let requestParam: [String : Any] = ["eventType": 3, "userName": user.username]
                            
                            UserCenterApiTool.notify(provider: weakSelf.userProvider, requestParam: requestParam, complete: { (model) in
                                if model?.code == 200 {
                                    NotificationCenter.default.post(name: GlobalNotificationName.didRevokeFriend.name, object: nil, userInfo: ["userName" : user.username])
                                }
                            }) { (error) in
                                
                            }
                            
                            MBProgressHUD_JChat.show(text: "删除好友成功", view: weakSelf.view)
                            /// 筛选分组的 好友数组
                            if var userss: [JMSGUser] = weakSelf.data[user.displayName().firstCharacter()] {
                                /// 找出删除的好友
                                userss.remove(at: indexPath.row)
                                /// 如果分组内没有好友, 则删除分组
                                if userss.count == 0 {
                                    weakSelf.keys.removeAll { (t) -> Bool in
                                        return t == user.displayName().firstCharacter()
                                    }
                                } else {
                                    /// 删除指定好友后的数组, 更新回去
                                    weakSelf.data.updateValue(userss, forKey: user.displayName().firstCharacter())
                                }
                                DispatchQueue.main.after(0.5, execute: {
                                    weakSelf.contacterView.reloadData()
                                })
                            }
                        }
                    }
                }
            }
        })
        .disposed(by: bag)
    }
}

extension JCContactsViewController: UISearchControllerDelegate {
    func willPresentSearchController(_ searchController: UISearchController) {
        contacterView.isHidden = true
        navigationVC?.tabBarController?.tabBar.isHidden = true
    }
    func willDismissSearchController(_ searchController: UISearchController) {
        contacterView.isHidden = false
        let nav = searchController.searchResultsController as! BaseNavController
        nav.isNavigationBarHidden = true
        nav.popToRootViewController(animated: false)
        navigationVC?.tabBarController?.tabBar.isHidden = false
    }
}

//extension JCContactsViewController: JXPagingViewListViewDelegate {
//    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
//        listViewDidScrollCallback = callback
//    }
//
//
//    func listView() -> UIView {
//        return self.view
//    }
//
//    func listScrollView() -> UIScrollView {
//        return self.contacterView
//    }
//}

//extension JCContactsViewController: JXPagingViewListViewDelegate {
//    func listView() -> UIView {
//        return view
//    }
//
//    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
//        self.listViewDidScrollCallback = callback
//    }
//
//    func listScrollView() -> UIScrollView {
//        return self.contacterView
//    }
//
//    func listWillAppear() {
//        debugPrint("\(self.title ?? ""):\(#function)")
//    }
//
//    func listDidAppear() {
//        debugPrint("\(self.title ?? ""):\(#function)")
//    }
//
//    func listWillDisappear() {
//        debugPrint("\(self.title ?? ""):\(#function)")
//    }
//
//    func listDidDisappear() {
//        debugPrint("\(self.title ?? ""):\(#function)")
//    }
//}

extension JCContactsViewController: JXSegmentedListContainerViewListDelegate {
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        listViewDidScrollCallback = callback
    }


    func listView() -> UIView {
        return self.view
    }

    func listScrollView() -> UIScrollView {
        return self.contacterView
    }
}

extension JCContactsViewController {
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .backgroundStyleOpaque, .showShadowImage]
    }
}
